<template>
  <div class="content">
    <n-row>
      <!-- 当前系统注册人数 -->
      <n-col :span="4">
        <n-card class="stat-card">
          <div class="card-inner-container" :style="{ backgroundColor: '#f0f8ff' }">
            <n-flex>
              <n-icon size="60" color="#f9e9cd" style="margin-top: 10px;" class="first" :style="{ backgroundColor: '#3e8e41' }">
                <UserCircle></UserCircle>
              </n-icon>
              <div>
                <n-flex vertical style="margin-left: 70px;margin-top: -80px">
                  <span style="color: #35333c;margin-left: 10px;font-size: 16px">当前注册人数</span>
                  <span class="icon-text" style="color: black;">{{ stats.user_count }}</span>
                </n-flex>
              </div>
            </n-flex>
          </div>
        </n-card>
      </n-col>

      <!-- 当前在行车辆数 -->
      <n-col :span="4">
        <n-card class="stat-card">
          <div class="card-inner-container" :style="{ backgroundColor: '#e8f7ff' }">
            <n-flex>
              <n-icon size="60" color="#f9e9cd" style="margin-top: 10px;" :style="{ backgroundColor: '#f39c12' }">
                <AccessPoint></AccessPoint>
              </n-icon>
              <div>
                <n-flex vertical style="margin-left: 70px;margin-top: -80px">
                  <span style="color: #35333c;margin-left: 10px;font-size: 16px">行驶车辆数</span>
                  <span class="icon-text" style="color: black;">{{ stats.riding_machine_count }}</span>
                </n-flex>
              </div>
            </n-flex>
          </div>
        </n-card>
      </n-col>

      <!-- 当前违停车辆的数量 -->
      <n-col :span="4">
        <n-card class="stat-card">
          <div class="card-inner-container" :style="{ backgroundColor: '#f9f7e8' }">
            <n-flex>
              <n-icon size="60" color="#f9e9cd" style="margin-top: 10px;" :style="{ backgroundColor: '#e74c3c' }">
                <AccessPointOff></AccessPointOff>
              </n-icon>
              <div>
                <n-flex vertical style="margin-left: 70px;margin-top: -80px">
                  <span style="color: #35333c;margin-left: 10px;font-size: 16px">违停车辆数</span>
                  <span class="icon-text" style="color: black;">{{ stats.illegal_machine_count }}</span>
                </n-flex>
              </div>
            </n-flex>
          </div>
        </n-card>
      </n-col>

      <!-- 当前骑行区域数 -->
      <n-col :span="4">
        <n-card class="stat-card">
          <div class="card-inner-container" :style="{ backgroundColor: '#f0fff4' }">
            <n-flex>
              <n-icon size="60" color="#f9e9cd" style="margin-top: 10px;" :style="{ backgroundColor: '#3498db' }">
                <SmartHome></SmartHome>
              </n-icon>
              <div>
                <n-flex vertical style="margin-left: 70px;margin-top: -80px">
                  <span style="color: #35333c;margin-left: 10px;font-size: 16px">当前区域数量</span>
                  <span class="icon-text" style="color: black;">{{ stats.all_area_count }}</span>
                </n-flex>
              </div>
            </n-flex>
          </div>
        </n-card>
      </n-col>

      <!-- 当前全部车辆 -->
      <n-col :span="4">
        <n-card class="stat-card">
          <div class="card-inner-container" :style="{ backgroundColor: '#f3f4f6' }">
            <n-flex>
              <n-icon size="60" color="#f9e9cd" style="margin-top: 10px;" :style="{ backgroundColor: '#9b59b6' }">
                <Bike></Bike>
              </n-icon>
              <div>
                <n-flex vertical style="margin-left: 70px;margin-top: -80px">
                  <span style="color: #35333c;margin-left: 10px;font-size: 16px">全部车辆数量</span>
                  <span class="icon-text" style="color: black;">{{ stats.all_machine_count }}</span>
                </n-flex>
              </div>
            </n-flex>
          </div>
        </n-card>
      </n-col>
    </n-row>

    <!-- 折线图和饼图的布局 -->
    <div class="charts-container">
      <v-chart class="chart" :option="option" />
      <v-chart class="chart pie-chart" :option="pieoption" />
    </div>

    <div class="charts-container">
      <v-chart class="chart" :option="usageOption" />
      <v-chart class="chart" :option="rankOption" />
    </div>

  </div>
</template>

<script setup>
import { NRow, NCol, NCard, NIcon, NFlex } from 'naive-ui'
import { UserCircle, AccessPointOff, AccessPoint, Bike, SmartHome } from '@vicons/tabler'
import { ref,onMounted} from 'vue';
import axiosInstance from '@/utils/axios';
import VChart from 'vue-echarts';
import { use } from 'echarts/core';
import { BarChart, LineChart, PieChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, GridComponent, LegendComponent } from 'echarts/components';
import { UniversalTransition, LabelLayout } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';


// 数据存储
const stats = ref({
  user_count: 0,
  all_machine_count: 0,
  riding_machine_count: 0,
  illegal_machine_count: 0,
  all_area_count: 0,
  area_machine_count: {},
  week_order_count: {},
  week_order_count_last_week: {},
  top_10_machines: [],
  top_10_users: []
});

const areas = ref([]);

onMounted(async () => {
  try {
    const response = await axiosInstance.get('/api/get_anaylze'); // 请求后端接口
    if (response.data.success) {
      stats.value = response.data.data[0]; // 获取返回的统计数据 
    }

    // 请求区域列表数据
    const areaResponse = await axiosInstance.post('/api/area_list', { page: 1, page_size: 100 });
    if (areaResponse.data.success) {
      areas.value = areaResponse.data.data; // 获取返回的区域列表
    }

    updateCharts(); // 更新图表数据
  } catch (error) {
    console.error('Error fetching statistics:', error);
  }
});

const updateCharts = () => {
  // 更新折线图数据
  option.value.series[0].data = stats.value.week_order_count_last_week;
  option.value.series[1].data = stats.value.week_order_count;

  // 更新区域分布的饼图数据
  const areaData = Object.entries(stats.value.area_machine_count).map(([areaId, count]) => {
    // 转换为字符串，确保与后端返回的区域 ID 匹配
    const areaIdStr = areaId.toString();
    const area = areas.value.find(a => a.area_id === areaIdStr);
    const areaName = area ? area.area_name : `区域 ${areaId}`; // 如果找不到区域名称，默认显示“区域X”
    return {
      value: count,
      name: areaName
    };
  });
  pieoption.value.series[0].data = areaData;

  // 更新车辆使用统计条形图
  usageOption.value.yAxis.data = stats.value.top_10_machines.map(item => item[0]);
  usageOption.value.series[0].data = stats.value.top_10_machines.map(item => item[1]);

  // 更新车辆使用排名
  rankOption.value.series[0].data = stats.value.top_10_users.map(item => item[1]);
  rankOption.value.yAxis.data = stats.value.top_10_users.map(item => item[0]);

}

use([TitleComponent, TooltipComponent, GridComponent, LegendComponent, BarChart, CanvasRenderer, LineChart, UniversalTransition, PieChart, LabelLayout]);


// 折线图配置项
const option = ref({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['上周各天骑行次数', '本周各天骑行次数']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'] // 周一到周日
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '上周各天骑行次数',
      type: 'line',
      data: [5, 8, 7, 6, 9, 5, 8],
      smooth: true,
    },
    {
      name: '本周各天骑行次数',
      type: 'line',
      data: [20, 15, 18, 25, 30, 22, 27],
      smooth: true,
    }
  ]
});

// 饼图配置项
const pieoption = ref({
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: '5%',
    left: 'center'
  },
  series: [
    {
      name: '区域电动车分布图',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 40,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
      ]
    }
  ]
});

// 车辆使用统计条形图配置项
const usageOption = ref({
  title: {
    text: '上周车辆使用统计'
  },
  tooltip: {
    trigger: 'axis'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  axisLabel: {
  color: "#000",
  interval: 0,
  formatter: function(value) {
    if (value.length > 12) {
      return value.substring(0, 12) + "...";
    } else {
      return value;
    }
  }
 },
  yAxis: {
    type: 'category',
    data: [] // 电动车编号
  },
  xAxis: {
    type: 'value'  // 将 X 轴设置为数值轴
  },
  series: [
    {
      name: '使用次数',
      type: 'bar',
      data: [], // 每辆车的使用次数
      itemStyle: {
        color: '#56c8e8'
      }
    }
  ]
});

const rankOption = ref({
  title: {
    text: '上周用户使用排名'
  },
  tooltip: {
    trigger: 'item'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  yAxis: {
    type: 'category',
    data: [] // 电动车编号
  },
  xAxis: {
    type: 'value'  // 将 X 轴设置为数值轴
  },
  axisLabel: {
  color: "#000",
  interval: 0,
  formatter: function(value) {
    if (value.length > 12) {
      return value.substring(0, 12) + "...";
    } else {
      return value;
    }
  }
 },
  series: [
    {
      name: '使用次数',
      type: 'bar',
      data: [], // 每辆车的使用次数
      itemStyle: {
        color: '#ff9e9d'
      }
    }
  ]
});
</script>

<style scoped>
.chart {
  height: 400px;
  width: 500px; /* 缩小折线图宽度 */
  margin-top: 40px;
}

/* 饼图的样式 */
.pie-chart {
  height: 300px;
  width: 400px; /* 缩小饼图宽度 */
}

/* 图表容器，使用 flexbox 布局 */
.charts-container {
  display: flex;
  gap: 5px; /* 减小间距 */
  margin-top: 40px;
  margin-left: 10px;
}

/* 样式调整 */
.content {
  margin-left: 60px;
  margin-top: 20px;
  width: 100%;
}

.n-col {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding-left: 10px;
}

.stat-card {
  width: 100%;
  border: none;
  position: relative;
  background-color: white;
}

.stat-card:not(:last-child) {
  margin-right: 20px;
}

.stat-card::after {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  width: 1px;
  height: 100%;
  background-color: #ddd;
}

.n-col .n-card {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.icon-with-text {
  display: flex;
  align-items: center;
}

.icon-text {
  margin-left: 40px;
  font-size: 40px;
  font-weight: bold;
  margin-top: -10px;
}

.card-inner-container {
  background-color: white;  /* 设置背景为白色 */
  border: 2px solid rgba(20,81,154,0.5);
  padding: 10px;  /* 内边距，防止内容贴边 */
  border-radius: 8px;  /* 圆角效果 */
  width: 180px;
  height: 80px;
  transition: box-shadow 0.3s ease, background-color 0.3s ease;
}

.card-inner-container:hover {
  box-shadow: 0 0 10px 5px rgba(0, 0, 255, 0.5);
}

.n-icon {
  transition: background-color 0.3s ease; /* 平滑过渡 */
}

.n-icon:hover {
  background-color: rgba(0, 0, 255, 0.5); /* 图标背景颜色变绿色 */
  border-radius: 8px;  /* 圆角效果 */
}
</style>
